import React from 'react';
import { connect } from 'dva';
import { Table, Row, Col, Form, Input, Radio, DatePicker, Select, Button, Popconfirm, message } from 'antd';
const R = require('ramda');
const dateFormat = 'YYYY-MM-DD';
const { RangePicker } = DatePicker;
import RightContacts from '../../../utils/RightConstants';
import OutbuyDetail from '../../../components/outbuy/components/OutbuyDetail';
import OrderDetail from '../../../components/order/components/OrderDetail';
import RightBox from "../../../components/commons/RightBox";
import Constants from "../../../utils/Constants";
import EditOutbuy from '../../../components/outbuy/components/EditOutbuy';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
export default connect(({ customerManage, drawer, orderManage, businessAgreement, statement, capital, customerReport, blacklist }) => ({ customerManage, drawer, orderManage, businessAgreement, statement, capital, customerReport, blacklist }))(
    Form.create()(class customerDetails extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                open: false,
                outbuyId: ''
            }
        }

        componentDidMount() {
            this.props.dispatch({ type: 'customerManage/getBuyerList', payload: { status: "4", page: Constants.DEFAULT_PAGE } });
        }


        handleOpen = (type, record, disabled) => {
            var id = record && record.id ? record.id : null;
            if (id) {
                this.props.dispatch({
                    type: 'customerManage/getBuyerById',
                    payload: { id }
                })
                this.props.dispatch({ type: 'payer/query', payload: { page: Constants.DEFAULT_PAGE } })
                this.props.dispatch({ type: 'requirement/query', payload: { page: Constants.DEFAULT_PAGE } })
            }

            this.editOutbuy.handleOpen(type, id, disabled);
        }


        onView = (record) => {
            this.handleOpenDetail(record, false, {}, "1", true);
        }



        handleAddOrder = (record) =>{
            if(!record.manager || !record.waiter || !record.tgmanager){
                message.error("请确认跟单经理、业务经理、通关经理是否都已经全部分配完毕！");
                return;
            }
            this.setState({ outbuyId: record.id });
            this.props.dispatch({type: 'customerManage/queryCustomerManageList', payload: {status: 4 }});//查询供应商列表
            this.props.dispatch({type: 'customerManage/getBuyerList', payload: { status: 4, ready: true, page: Constants.DEFAULT_PAGE }});//查询境外买家
            this.refs.orderDetail.handleOpen(false, false, false, false, {}, "1");
        }

        handleOpenDetail = (record, customerDisabled, searchConditions, tabActiveKey, editCustomerDisable) => {
            this.props.dispatch({
                type: 'customerManage/getBuyerById',
                payload: {
                    id: record.id,
                    onSuccess: () => {
                        this.props.dispatch({ type: 'payer/query', payload: { buyerId: record.id, page: Constants.DEFAULT_PAGE } });
                        this.props.dispatch({ type: 'requirement/query', payload: { buyerId: record.id, page: Constants.DEFAULT_PAGE } });
                        this.props.dispatch({ type: 'orderManage/queryOrderManageList', payload: { buyerId: record.id, page: this.props.orderManage.page, status: 1 } });

                        //this.props.dispatch({type: 'customerManage/getListByCstIdForPage', payload: {cstId: record.id, page: this.props.customerManage.marketInfoPage}}); //营销线索
                        this.refs.outbuyDetail.handleOpen(customerDisabled, searchConditions, tabActiveKey, record.id, editCustomerDisable, "customerDetail");
                    }
                }
            });



        }


        handleSearch = () => {
            let values = this.props.form.getFieldsValue();
            let newPage = this.props.customerManage.buyerPage;
            newPage.page = 1;
            let time = values.time;
            this.props.dispatch({
                type: 'customerManage/getBuyerList',
                payload: {
                    buyerNo: values.buyerNo,
                    name: values.name,
                    manager: values.manager,
                    waiter: values.waiter,
                    status: values.status,
                    beginTime: R.isNil(time) || R.isEmpty(time) ? null : time[0].format(dateFormat),
                    endTime: R.isNil(time) || R.isEmpty(time) ? null : time[1].format(dateFormat),
                    page: newPage
                }
            });
        };


        columns = [
            { title: '外商编码', dataIndex: 'buyerNo', key: 'buyerNo' },

            { title: '外商名称', dataIndex: 'name', key: 'name', },

            {
                title: '业务经理', render(record) {
                    if (R.isNil(record.managerName) || R.isEmpty(record.managerName)) {
                        return "未分配";
                    } else {
                        return record.managerName;
                    }
                }
            },

            {
                title: '跟单经理', render(record) {
                    if (R.isNil(record.waiterName) || R.isEmpty(record.waiterName)) {
                        return "未分配";
                    } else {
                        return record.waiterName;
                    }
                }
            },

            { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },

            {
                title: '操作', key: 'key_oprator',

                render: (text, record, index) => {

                    let infoMaintenance = <RightBox resource={RightContacts.OUTBUY.OUTBUY_MANAGE_INFOMAINTENANCE} split={true}><a href="#" onClick={this.onView.bind(this, record)}>信息维护</a></RightBox>;
                    let infoEdit = <RightBox resource={RightContacts.OUTBUY.OUTBUY_MANAGE_UPDATE}><a href="#" onClick={this.handleOpen.bind(this, 'edit', record, false)}>编辑</a><span className="ant-divider" /> </RightBox>;
                    let infoView = <span><a href="#" onClick={this.handleOpen.bind(this, 'view', record, true)}>查看</a></span>;
                    let addOrder = <RightBox resource={RightContacts.OUTBUY.OUTBUY_MANAGE_ADDORDER}><a href="#" onClick={this.handleAddOrder.bind(this, record)}>添加订单</a></RightBox>
                    return (
                        <span>
                            {record.status === '1' || record.status === '3' ? infoEdit : ''}
                            {record.status === '4' ? <span>{infoMaintenance}{addOrder}</span> : ''}
                            {
                                record.status === '1' || record.status === '3' ? <RightBox split={true} resource={RightContacts.OUTBUY.OUTBUY_MANAGE_DELETE}><span>
                                    <Popconfirm placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除？'}
                                        onConfirm={() => {
                                            this.props.dispatch({
                                                type: 'customerManage/deleteBuyerById',
                                                payload: {
                                                    id: record.id,
                                                    onSuccess: ()=> this.handleSearch()

                                                }
                                            })
                                        }} okText="是" cancelText="否">
                                        <a href="#" disabled={this.props.disabled}>删除</a>
                                    </Popconfirm>
                                </span></RightBox> : ""
                            }
                            {record.status === '4'? '' : infoView}
                        </span>
                    );
                }
            }
        ];


        render() {
            let formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };
            const { getFieldDecorator } = this.props.form;
            let values = this.props.form.getFieldsValue();
            let time = values.time;
            let pagination = {
                showTotal: total => `共 ${total} 条数据`,
                pageSize: this.props.customerManage.buyerPage.size,
                total: this.props.customerManage.buyerPage.totalRow,
                showSizeChanger: true,
                current: this.props.customerManage.buyerPage.page,
                onShowSizeChange: (current, size) => {
                    let newPage = this.props.customerManage.buyerPage;
                    newPage.size = size;
                    newPage.page = 1;
                    this.props.dispatch({
                        type: 'customerManage/getBuyerList',
                        payload: {
                            buyerNo: values.buyerNo,
                            name: values.name,
                            manager: values.manager,
                            waiter: values.waiter,
                            status: values.status,
                            beginTime: R.isNil(time) || R.isEmpty(time) ? null : time[0].format(dateFormat),
                            endTime: R.isNil(time) || R.isEmpty(time) ? null : time[1].format(dateFormat),
                            page: newPage
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    let newPage = this.props.customerManage.buyerPage;
                    newPage.page = pageNumber;
                    this.props.dispatch({
                        type: 'customerManage/getBuyerList',
                        payload: {
                            buyerNo: values.buyerNo,
                            name: values.name,
                            manager: values.manager,
                            waiter: values.waiter,
                            status: values.status,
                            beginTime: R.isNil(time) || R.isEmpty(time) ? null : time[0].format(dateFormat),
                            endTime: R.isNil(time) || R.isEmpty(time) ? null : time[1].format(dateFormat),
                            page: newPage
                        }
                    });
                }
            }



            return (
                <div>

                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'外商编号'}>{getFieldDecorator('buyerNo')(<Input />)}</FormItem></Col>
                        <Col span={7}><FormItem {...formItemLayout} label={'外商名称'}>{getFieldDecorator('name')(<Input />)}</FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'业务经理'}>{getFieldDecorator('manager')(<Input />)}</FormItem></Col>
                        <Col span={7}><FormItem {...formItemLayout} label={'跟单经理'}>{getFieldDecorator('waiter')(<Input />)}</FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={7}>
                            <FormItem {...formItemLayout} label={'创建时间'}>
                                {getFieldDecorator('time', {})(
                                    <RangePicker
                                        style={{ width: 265 }}
                                        showTime={{ format: 'YYYY-MM-DD' }}
                                        format="YYYY-MM-DD"
                                        placeholder={['开始时间', '结束时间']}
                                    />
                                )}
                            </FormItem>
                        </Col>
                    </Row>

                    <Row>
                        <Col span={7}>
                            <FormItem {...formItemLayout} label={'状态'}>
                                {getFieldDecorator('status', {
                                    initialValue: "4"
                                })(

                                    <RadioGroup style={{ width: 800 }}>
                                        <Radio value="1">待申请</Radio>
                                        <Radio value="2">待审核</Radio>
                                        <Radio value="3">待补充资料</Radio>
                                        <Radio value="4">审核通过</Radio>
                                        <Radio value="5">审核不通过</Radio>
                                    </RadioGroup>
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12} style={{ float: 'right' }}>
                            <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleSearch.bind(this)}>查询</Button>
                            <RightBox resource={RightContacts.OUTBUY.OUTBUY_MANAGE_ADD}><Button type="primary" icon="plus" style={{ marginRight: 5 }} onClick={this.handleOpen.bind(this, 'add', null, false)}>添加外商</Button></RightBox>
                        </Col>
                    </Row>

                    <Table rowKey="id" dataSource={this.props.customerManage.buyerList} columns={this.columns} bordered={true} size={'middle'} pagination={pagination} />


                    <EditOutbuy wrappedComponentRef={(inst) => this.editOutbuy = inst} dataSource={this.props.customerManage.buyer} handleSearch={this.handleSearch} />


                    <OutbuyDetail ref={"outbuyDetail"} {...this.props.customerManage}
                        orderManage={this.props.orderManage}
                        customerManage={this.props.customerManage}
                        statement={this.props.statement}
                        dispatch={this.props.dispatch}
                        capital={this.props.capital}
                        blacklist={this.props.blacklist}
                        handleSearch={this.handleSearch} />

                    <OrderDetail ref={"orderDetail"} {...this.props.orderManage} {...this.props.customerManage}
                                 dispatch={this.props.dispatch} refreshList={this.handleSearch} outbuyId={this.state.outbuyId} />

                </div>
            )
        }
    })


)
